package server;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.Domain;

public class PutCache {
	@SuppressWarnings("unchecked")
	public static void putCacheDomain(Domain domain1,String nameCache,int size)
	{
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		if(cache.containsKey(nameCache))
		{
			ArrayList<Domain> lastupdate = (ArrayList<Domain>)cache.get(nameCache);
        	if(lastupdate.size()>size)
        	{
        		lastupdate.remove(0);
        	}
        	int check=0;
        	for (int i = 0; i < lastupdate.size(); i++) {
				if(lastupdate.get(i).getDomain().equals(domain1.getDomain()))
					check=1;
			}
        	if(check==0)
        		lastupdate.add(domain1);
        	cache.put(nameCache, lastupdate);
		} else {
			ArrayList<Domain> lastupdate = new ArrayList<Domain>();
        	if(!lastupdate.contains(domain1))
        		lastupdate.add(domain1);
        	cache.put(nameCache, lastupdate);
		}
	}
	@SuppressWarnings("unchecked")
	public static void putCacheList(String name,String nameCache,int num)
	{
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
		   e.printStackTrace();
		   
		}
    	if(cache.containsKey(nameCache))
		{
			ArrayList<String> siteview = (ArrayList<String>)cache.get(nameCache);
        	if(siteview.size()>num)
        	{
        		siteview.remove(0);
        	}
        	if(!siteview.contains(name))
        		siteview.add(name);
        	cache.put(nameCache, siteview);
		} else {
			ArrayList<String> siteview = new ArrayList<String>();
        	if(!siteview.contains(name))
        		siteview.add(name);
        	cache.put(nameCache, siteview);
		}
	}
}
